package com.company.cloud.company.modules.mgr.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.company.cloud.common.bean.LoginSimpleUserInfo;
import com.company.cloud.common.constant.BaseConstant;
import com.company.cloud.common.utils.CheckUtils;
import com.company.cloud.company.modules.base.entity.BaseProfitConfig;
import com.company.cloud.company.modules.base.service.BaseProfitConfigService;
import com.company.cloud.company.modules.cache.utils.CompanyConvertUtils;
import com.company.cloud.company.modules.mgr.controller.req.BaseProfitQueryPageParam;
import com.company.cloud.company.modules.mgr.controller.req.BaseProfitSaveParam;
import com.company.cloud.company.modules.api.response.BaseProfitConfigResp;
import com.company.cloud.company.modules.mgr.service.BaseProfitMgrService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class BaseProfitMgrServiceImpl implements BaseProfitMgrService {

    @Autowired
    private BaseProfitConfigService baseProfitConfigService;

    @Override
    public IPage<BaseProfitConfigResp> query(BaseProfitQueryPageParam params, String companyNo) {
        IPage<BaseProfitConfig> page = baseProfitConfigService.page(new Page<BaseProfitConfig>(params.getPage(), params.getRows()),
                new QueryWrapper<BaseProfitConfig>()
                        .eq(CheckUtils.hasText(companyNo), "company_no", companyNo)
                        .eq(CheckUtils.hasText(params.getIsCustCheck()), "is_cust_check", params.getIsCustCheck())
                        .eq(CheckUtils.hasText(params.getIsAutoCheck()), "is_auto_check", params.getIsAutoCheck())
                        .eq(CheckUtils.hasText(params.getProfitWay()), "profit_way", params.getProfitWay())
                        .eq("rows_state", BaseConstant.EnabledEnum.ENABLED.getCode())
        );

        return page.convert(CompanyConvertUtils::getBaseProfitConfigResp);
    }

    @Override
    public void saveOrEdit(BaseProfitSaveParam params, String companyNo, LoginSimpleUserInfo userInfo) {
        BaseProfitConfig entity = CompanyConvertUtils.getBaseProfitConfig(params, userInfo.getCompanyNo());
        BaseProfitConfig old = baseProfitConfigService.getById(userInfo.getCompanyNo());
        if (old == null) {
            entity.addCreateParam(userInfo);
            entity.addEditParam(userInfo);
            baseProfitConfigService.save(entity);
        } else {
            entity.addEditParam(userInfo);
            baseProfitConfigService.updateById(entity);
        }
    }

    @Override
    public BaseProfitConfigResp get(String companyNo) {
        BaseProfitConfig entity = baseProfitConfigService.getById(companyNo);
        return CompanyConvertUtils.getBaseProfitConfigResp(entity);
    }
}
